<?php
/**
 * 测试每月结算功能
 * 使用方法: php test-monthly-billing.php
 */

require_once __DIR__ . '/vendor/autoload.php';

use app\model\BizModel;
use app\model\BizPayRecordModel;
use app\model\BizGoodsTicketModel;
use app\model\BillModel;
use support\Db;

echo "开始测试每月结算功能...\n";

try {
    // 获取当前月份
    $currentMonth = date('Y-m');
    echo "当前月份: {$currentMonth}\n";
    
    // 查询所有商家
    $bizList = BizModel::all();
    echo "找到商家数量: " . count($bizList) . "\n";
    
    foreach ($bizList as $biz) {
        echo "\n处理商家 {$biz->id} ({$biz->name})\n";
        
        // 检查是否已经结算过当前月份
        if ($biz->recent_bill_date === $currentMonth) {
            echo "商家 {$biz->id} 已结算过 {$currentMonth}，跳过\n";
            continue;
        }
        
        // 统计未结算的随心付记录
        $payRecords = BizPayRecordModel::where('biz_id', $biz->id)
            ->where('pay_status', 1) // 已支付
            ->where('bill_id', 0) // 未结算
            ->get();
        
        $payRecordsTotal = 0;
        foreach ($payRecords as $record) {
            $payRecordsTotal += $record->pay_money * 0.7; // 假设商家获得70%
        }
        $payRecordsTotal = round($payRecordsTotal, 2);
        
        echo "未结算随心付记录数量: " . count($payRecords) . ", 金额: {$payRecordsTotal}\n";
        
        // 统计未结算的核销码
        $tickets = BizGoodsTicketModel::where('biz_id', $biz->id)
            ->where('status', 1) // 已使用
            ->where('bill_id', 0) // 未结算
            ->get();
        
        $ticketsTotal = 0;
        foreach ($tickets as $ticket) {
            $ticketsTotal += $ticket->money * 0.7; // 假设商家获得70%
        }
        $ticketsTotal = round($ticketsTotal, 2);
        
        echo "未结算核销码数量: " . count($tickets) . ", 金额: {$ticketsTotal}\n";
        
        // 计算总金额
        $totalAmount = $payRecordsTotal + $ticketsTotal;
        echo "总结算金额: {$totalAmount}\n";
        
        if ($totalAmount > 0) {
            echo "将创建结算单，金额: {$totalAmount}\n";
        } else {
            echo "无结算金额\n";
        }
    }
    
    echo "\n测试完成！\n";
    
} catch (Exception $e) {
    echo "测试异常: " . $e->getMessage() . "\n";
} 